package com.netease.financial.base.share.helper;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.netease.financial.R;
import com.netease.financial.base.share.model.ShareHolder;
import com.netease.financial.common.config.NfsConfig;
import com.netease.financial.common.util.ImageUtil;

import im.yixin.sdk.api.IYXAPI;
import im.yixin.sdk.api.SendMessageToYX;
import im.yixin.sdk.api.YXAPIFactory;
import im.yixin.sdk.api.YXMessage;
import im.yixin.sdk.api.YXWebPageMessageData;
import im.yixin.sdk.util.BitmapUtil;

/**
 * Created by wyf on 6/28/15.
 */
public class EasyChatHelper {

    private IYXAPI mYxApi;
    private Context mContext;

    public EasyChatHelper(Context context) {
        mContext = context;
        mYxApi = YXAPIFactory.createYXAPI(context, NfsConfig.getEasyChatAppId());
        mYxApi.registerApp();
    }

    public static EasyChatHelper createHelper(Context context) {
        return new EasyChatHelper(context);

    }

    public boolean sendToEasyChatFriend(ShareHolder holder) {
        return share(holder, SendMessageToYX.Req.YXSceneSession);
    }

    public boolean shareOnEasyChatMoment(ShareHolder holder) {
        return share(holder, SendMessageToYX.Req.YXSceneTimeline);
    }

    private boolean share(ShareHolder holder, int scene) {

        YXWebPageMessageData webPage = new YXWebPageMessageData();
        webPage.webPageUrl = holder.webUrl;
        YXMessage msg = new YXMessage(webPage);
        msg.title = holder.title;
        msg.description = holder.description;

        msg.thumbData = BitmapUtil.bmpToByteArray(getThumbnail(holder.imageUrl), true);
        SendMessageToYX.Req req = new SendMessageToYX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        req.scene = scene;
        mYxApi.sendRequest(req);
        return true;
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    private Bitmap getThumbnail(String imageUrl) {
        Bitmap thumb = ImageUtil.getThumbnail(imageUrl);
        if (thumb == null) {
            thumb = BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher);
        }
        return com.netease.financial.common.util.BitmapUtil.cropCenterBitmap(thumb, 120, 120);
    }

}
